package org.buptsse.ui;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;


public class MenuAddGridView extends Activity {
    GridView gridview;
    SimpleAdapter gridviewAdapter;
    Button openFolder,addSingle,backFolder;
    String sdcardFilePath,thisFilePath,selectFilePath;
    private String actionUrl = "http://1.rebook.sinaapp.com/receive_file.php";
    private Handler dialogHandler = null;
    private static final int PROGRESSDIALOG = 2;
    private final int finish = 0;
    private OutputStream os;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.menuaddgridviewwq);
        
        sdcardFilePath=Environment.getExternalStorageDirectory().getAbsolutePath();
        thisFilePath=sdcardFilePath;
        
        openFolder=(Button) this.findViewById(R.id.MenuAddGridView_button_openfolder);
        openFolder.setVisibility(View.INVISIBLE);
        openFolder.setOnClickListener(new buttonOnClickListener());
        addSingle=(Button) this.findViewById(R.id.MenuAddGridView_button_addSingle);
        addSingle.setVisibility(View.INVISIBLE);
        addSingle.setOnClickListener(new buttonOnClickListener());
        //addFolder=(Button) this.findViewById(R.id.MenuAddGridView_button_addFolder);
        //addFolder.setVisibility(View.INVISIBLE);
        //addFolder.setOnClickListener(new buttonOnClickListener());
        backFolder=(Button) this.findViewById(R.id.MenuAddGridView_button_backFolder);
        backFolder.setOnClickListener(new buttonOnClickListener());
        
        gridview=(GridView) this.findViewById(R.id.MenuAddGridView_gridview);
      
        updategridviewAdapter(thisFilePath);
        
        dialogHandler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case finish:
					dismissDialog(PROGRESSDIALOG);
				}
			}
		};
        
        
        gridview.setOnItemClickListener(new OnItemClickListener(){
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);
                selectFilePath=(String) item.get("ItemFilePath");
                
                if(item.get("type").equals("isDirectory"))
                {
                    openFolder.setVisibility(View.VISIBLE);
                    addSingle.setVisibility(View.INVISIBLE);
                    //addFolder.setVisibility(View.VISIBLE);
                }
                else 
                {
                    openFolder.setVisibility(View.INVISIBLE);
                    addSingle.setVisibility(View.VISIBLE);
                    //addFolder.setVisibility(View.INVISIBLE);
                }
                
            }});
            this.setResult(0);
    }
    
    protected Dialog onCreateDialog(int id) {  
        // TODO Auto-generated method stub  
      if(id==2){
        	return this.buildProgressDialog(MenuAddGridView.this);
        }  
      else
      {
    	  return null;
      }
    }
    
    private Dialog buildProgressDialog(Context context)
    {
    	Dialog resultDialog = new ProgressDialog(this);;
    	resultDialog.setTitle("正在上传……");
    	((ProgressDialog) resultDialog).setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	return resultDialog;

    }
    
    protected void onPrepareDialog(int id, Dialog dialog) {  
        // TODO Auto-generated method stub  
        super.onPrepareDialog(id, dialog);  
        switch (id) {
		case PROGRESSDIALOG:
			new GetData().start();
			break;
		}
    }  
    
    class GetData extends Thread{
    	public void run(){
    		uploadFile(actionUrl);
    		if(dialogHandler!=null)dialogHandler.sendEmptyMessage(finish);
    	}
    }
    
    private void uploadFile(String uploadUrl)
    {
  	  try
  	  {
  	  			URL url = new URL("http://1.rebook.sinaapp.com/receive_file.php"); //文件接收的CGI,不一定是JSP的
  	  			
  	  			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  	  			conn.setRequestMethod("POST");
  	  			conn.setDoOutput(true);

  	  			String BOUNDARY = "---------------------------7d4a6d158c9"; // 分隔符
  	  			
  	  			
  	  			StringBuffer sb = new StringBuffer();
  	  			sb.append("--");
  	  			sb.append(BOUNDARY);
  	  			sb.append("\r\n");
  	  			sb.append("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
            + thisFilePath.substring(thisFilePath.lastIndexOf("/") + 1)
            + "\""+"\r\n");
  	  			sb.append("Content-Type: application/octet-stream\r\n\r\n");
  	  			
  	  			byte[] data = sb.toString().getBytes();
  	  			byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
  	  			
  	  			File file=new File(thisFilePath);
  	  			System.out.println("file length-->"+file.length());
  	  			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+BOUNDARY); //设置表单类型和分隔符
  				conn.setRequestProperty("Content-Length", String.valueOf(data.length+file.length()  + end_data.length)); //设置内容长度
  	  			
  	  			os = conn.getOutputStream();
  	  			os.write(data);
  	  			
  	  			
  	  			FileInputStream fis = new FileInputStream(new File(thisFilePath)); //要上传的文件
  	  			
  	  			int rn2;
  	  			byte[] buf2 = new byte[1024];
  	  			while((rn2=fis.read(buf2, 0, 1024))>0)
  	  			{	
  	  				os.write(buf2,0,rn2);
  	  				
  	  			}
  	  			
  	  			
  	  			os.write(end_data);
  	  			os.flush();
  	  			os.close();
  	  			fis.close();
  	  			
  	  			//得到返回的信息
  	  			InputStream is = conn.getInputStream();
  	  			InputStreamReader isr = new InputStreamReader(is, "utf-8");
  	  	        BufferedReader br = new BufferedReader(isr);
  	  	        String result = br.readLine();

  	  	        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
  	  			
  	  			byte[] inbuf = new byte[1024];
  	  			int rn;
  	  			while((rn=is.read(inbuf,0,1024))>0)
  	  			{
  	  				
  	  				System.out.write(inbuf,0,rn);
  	  				
  	  			}
  	  			is.close();

  	  		}
  	  		catch(Exception ee)
  	  		{
  	  			System.out.println("上传出错.--->"+ee.toString());
  	  		}	
    }
    
    private File[] folderScan(String path)
    {
        File file=new File(path);
        File[] files=file.listFiles();
        return files;
    }
    
    private void updategridviewAdapter(String filePath)
    {
        File[] files=folderScan(filePath);
        ArrayList<HashMap<String, Object>> lstImageItem = getFileItems(files);
        gridviewAdapter = new SimpleAdapter(MenuAddGridView.this,lstImageItem,R.layout.menuaddgridview_itemwq,new String[] {"ItemImage","ItemText"}, new int[] {R.id.MenuAddGridView_ItemImage,R.id.MenuAddGridView_ItemText});
        gridview.setAdapter(gridviewAdapter);
        gridviewAdapter.notifyDataSetChanged();
    }
    
    private ArrayList<HashMap<String, Object>> getFileItems(File[] files)
    {
        ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
        
        if(files==null)
        {
            return null;
        }
        for(int i=0;i<files.length;i++)
        {
            HashMap<String, Object> map = new HashMap<String, Object>();
            String fileName=files[i].getName();
            map.put("ItemText", fileName);
            if(files[i].isDirectory())
            {
                map.put("ItemImage", R.drawable.folderwq);
                map.put("type", "isDirectory");
            }
            else if(files[i].isFile())
            {
             
                    map.put("ItemImage", R.drawable.file);
                    map.put("type", "isOthers");
                
            }
            map.put("ItemFilePath", files[i].getAbsolutePath());
            
            lstImageItem.add(map);
        }
        return lstImageItem;
    }
    private ArrayList<String> getResultArrayList(ArrayList<HashMap<String, Object>> al)
    {
        ArrayList<String> musicResult=new ArrayList<String>();
        for(int i=0;i<al.size();i++)
        {
            HashMap<String, Object> map=al.get(i);
            String type=(String) map.get("type");
            String itemFilePath=(String) map.get("ItemFilePath");
            musicResult.add(itemFilePath);
            
        }
        return musicResult;
    }
    class buttonOnClickListener implements OnClickListener
    {
        ArrayList<String> musicResult;
        Intent intent;
        public void onClick(View v) {
            switch(v.getId())
            {
                case R.id.MenuAddGridView_button_openfolder:
                    updategridviewAdapter(selectFilePath);
                    thisFilePath=selectFilePath;
                    System.out.println("currentfile--->"+thisFilePath);
                    openFolder.setVisibility(View.INVISIBLE);
                    addSingle.setVisibility(View.INVISIBLE);
                    //addFolder.setVisibility(View.INVISIBLE);
                    break;
                case R.id.MenuAddGridView_button_addSingle:
                	thisFilePath=selectFilePath;
                    musicResult=new ArrayList<String>();
                    musicResult.add(selectFilePath);
                    System.out.println("currentfile--->"+thisFilePath);
                    //uploadFile(actionUrl);
                    showDialog(PROGRESSDIALOG);
                    break;
               
                case R.id.MenuAddGridView_button_backFolder:
                    if(!thisFilePath.equals(sdcardFilePath))
                    {
                        File thisFile=new File(thisFilePath);
                        String parentFilePath=thisFile.getParent();
                        updategridviewAdapter(parentFilePath);
                        thisFilePath=parentFilePath;
                        
                        openFolder.setVisibility(View.INVISIBLE);
                        addSingle.setVisibility(View.INVISIBLE);
                        //addFolder.setVisibility(View.INVISIBLE);
                    }
                    else
                    {
                        
                    }
                    System.out.println("currentfile--->"+thisFilePath);
                    break;
            }
        }
        
    }
    protected void onDestroy() {
        this.finish();
        super.onDestroy();
    }
    
}